package Test6.PETSHOP;

import Test6.LNode.*;

public class PetShop{
    private LinkList pets=new LinkList();

    public boolean add(Pet pet){
        if(pet==null){
            return false;
        }
        if(pet instanceof PetImpl p){
            Node p1=new Node(p);
            Node p2=this.pets.getHead();
            if(p2==null){
                this.pets.add(p1);
                return true;
            }
            while(p2.getNext()!=null){
                //判断年龄，姓名是否相等
                if(p.equals(p2.getData())){
                    return false;
                }
                p2=p2.getNext();
            }
            p2.setNext(p1);
        }
        return true;
    }
    public boolean delete(Pet pet){
        if(this.pets==null||pet==null){
            return false;
        }
        if(pet instanceof PetImpl p){
            Node p1=new Node(p);
            Node p2=this.pets.getHead();
            //遍历判断是否存在该宠物
            while(p2!=null){
                if(p1.equals(p2.getData())){
                    //删除宠物
                    Node prior=this.pets.getHead();
                    while(prior!=p2){
                        prior=prior.getNext();
                    }
                    prior.setNext(p2.getNext());
                    return true;
                }
                p2=p2.getNext();
            }
            return false;
        }
        return false;
    }
    public Node get(int index){
        //count用于计数
        int count=0;
        if(index<0||index>=this.size()){
            return null;
        }
        Node p=this.pets.getHead();
        while(p!=null){
            if(count==index){
                break;
            }
            count++;
            p=p.getNext();
        }
            return p;
    }
    public int size(){
        return this.pets.length();
    }

    @Override
    public String toString(){
        StringBuilder s=new StringBuilder();
        s.append("{");
        Node p=this.pets.getHead();
        while(p!=null){
            PetImpl ret=(PetImpl) p.getData();
            s.append(ret.toString()).append(",");
            p=p.getNext();
        }
        s.append("}");
        return s.toString();
    }


    public static void main(String[] args) {
        PetShop petShop=new PetShop();
        Pet pet1=new Cat("波斯猫",1);
        Pet pet2=new Cat("橘猫",2);
        Pet pet3=new Cat("折耳猫",1);
        Pet pet4=new Dog("柯基犬",1);
        Pet pet5=new Dog("波尔多狗",2);
        petShop.add(pet1);
        petShop.add(pet2);
        petShop.add(pet3);
        petShop.add(pet4);
        petShop.add(pet5);
        System.out.println(petShop.toString());
        petShop.delete(pet2);
        System.out.println(petShop.toString());
    }
}
